//6．修改程序清单16.17，
//使用struct names元素（在程序清单16.17后面的讨论中定义过），而不是double类型的数组。
//使用较少的元素，并用选定的名字显式初始化数组。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define NUM 6
#define LEN 40
typedef struct names {
    char first[LEN];
    char last[LEN];
} name;

void showarray(const name ar[], int n);

int mycomp(const void *p1, const void *p2);

int main(void) {
    name names[NUM] = {
            {"liang", "zhuge"},
            {"ming",  "xiao"},
            {"ming",  "kong"},
            {"fei",   "zhang"},
            {"yu",    "guan"},
            {"bei",   "liu"},
    };
    puts("Init list:");
    showarray(names, NUM);
    qsort(names, NUM, sizeof(name), mycomp);
    puts("\nSorted list:");
    showarray(names, NUM);
    return 0;
}


void showarray(const name ar[], int n) {
    int index;
    for (index = 0; index < n; index++) {
        printf("%s %s\n", ar[index].first, ar[index].last);
    }
}

int mycomp(const void *p1, const void *p2) {
    const name *a1 = (const name *) p1;
    const name *a2 = (const name *) p2;
    int comp = strncmp(a1->first, a2->first, LEN);
    if (comp == 0) {
        return strncmp(a1->last, a2->last, LEN);
    }
    return comp;
}
